package cn.com.zcode.exam.control;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.struts2.json.JSONException;
import org.apache.struts2.json.JSONUtil;

import cn.com.zcode.core.control.BaseActionSupport;
import cn.com.zcode.dic.control.ApplicationCache;
import cn.com.zcode.dic.jstl.DictionaryUtil;
import cn.com.zcode.dic.model.Dictionary;
import cn.com.zcode.exam.model.Answer;
import cn.com.zcode.exam.model.Examination;
import cn.com.zcode.exam.model.Paper;
import cn.com.zcode.exam.model.Question;
import cn.com.zcode.exam.model.StaticInfo;
import cn.com.zcode.exam.model.Wrong;
import cn.com.zcode.exam.service.ExamService;
import cn.com.zcode.user.model.User;

public class ExamAction extends BaseActionSupport<ExamService> {
	private static final long serialVersionUID = 1L;
	private int start;
	private int length;
	private String out;
	private boolean continueExam;

	private Examination examination;
	private Question question;
	private Answer answer;
	private List<Question> questions = new ArrayList<Question>();

	public ExamAction() {
		super();
	}

	public String loadRemainingQuestions() {
		String eid = this.examination.getId();
		boolean isForWrong = this.examination.isForWrong();
		this.questions = service.findRemainingQuestions(eid, isForWrong, length, out);
		return SUCCESS;

	}

	/**
	 * 用于在startinit页面中通过AJAX 判断是否有末完成的答题
	 * 
	 * @return
	 */
	public String getLastExamination() {
		String paperId = this.examination.getPaper().getId();
		this.examination = service.getLastExamination(paperId, this.getCurrentUser().getId());
		return SUCCESS;
	}

	/**
	 * 开始考试
	 * 
	 * @return
	 */
	public String startExam() {
		User user = this.getSessionAttribute("user", User.class);
		if (examination == null) {
			List<Paper> papers = service.findPaperByUser("pmp", user);
			this.addAttribute("papers", papers);
			return INPUT;
		} else {
			Paper paper = this.examination.getPaper();
			String paperId = paper.getId();
			this.examination = this.service.getStartExamination(user, paperId, continueExam);
		}
		return SUCCESS;
	}

	public String finishExam() throws JSONException {
		String eid = this.examination.getId();
		this.examination = this.service.saveFinishExamination(eid);
		List<Question> questions = this.examination.getQuestions();
		Map<String, StaticInfo> map = new HashMap<String, StaticInfo>();
		if (questions != null) {
			for (Question question : questions) {
				String chapter = question.getChapter();
				StaticInfo staticinfo = map.get(chapter);
				if (staticinfo == null) {
					String title = DictionaryUtil.title(chapter);
					staticinfo = new StaticInfo(title,0);
					map.put(chapter, staticinfo);
				}
				Answer answer = question.getAnswerInfo();
				if (answer == null || !answer.isCorrect()) {
					staticinfo.addNum();
				}else{
					staticinfo.addRight();
				}
			}

		}
		this.addAttribute("staticInfos_json", JSONUtil.serialize(map));
		this.addAttribute("staticInfos", map);
		return SUCCESS;
	}

	/**
	 * 提交答案
	 * 
	 * @return
	 */
	public String submitAnswer() {
		User user = this.getCurrentUser();
		answer.setAnswerDate(new Date());
		answer = service.addAnswer(answer);
		answer.setUserId(user.getId());
		int anstate = answer.getState();
		boolean iscorrect = answer.isCorrect();
		if (!iscorrect || anstate == Answer.STATE_UNSURE || anstate == Answer.STATE_CANFIXED) {
			String questionId = answer.getQuestionId();
			String userId = answer.getUserId();
			Wrong wrong = service.getWrong(userId, questionId);
			if (iscorrect) {
				if (wrong == null) {
					wrong = new Wrong(answer);
				} else if (anstate == Answer.STATE_CANFIXED) {
					wrong.setFixed(true);
				}
				if (anstate == Answer.STATE_UNSURE) {
					wrong.setUnsure(true);
				}

			} else {
				if (wrong == null) {
					wrong = new Wrong(answer);
				} else {
					String wrongAnswer = wrong.getUserAnswer();
					String currentAnswer = answer.getUserAnswer();
					if (wrongAnswer.indexOf(currentAnswer) == -1) {
						String[] wrarr = (wrongAnswer + "," + currentAnswer).split(",");
						Arrays.sort(wrarr);
						StringBuffer sb = null;
						for (String string : wrarr) {
							if (sb == null) {
								sb = new StringBuffer();
							} else {
								sb.append(",");
							}
							sb.append(string.trim());
						}
						wrong.setUserAnswer(sb.toString());
					}
				}
				wrong.addCount();
			}

			service.addWrong(wrong);
		}
		return SUCCESS;
	}

	/**
	 * 添加题目
	 * 
	 * @return
	 */
	public String addQuestion() {
		this.service.addQuestion(question);
		return SUCCESS;
	}

	public String myWrongs() {
		String type = "pmp";
		User user = this.getSessionAttribute("user", User.class);
		this.questions = this.service.findWrongQuestions(type, user.getId());
		List<Dictionary> dlist = ApplicationCache.getDictionaryByType(type);

		Map<String, StaticInfo> map = new LinkedHashMap<String, StaticInfo>();
		for (Dictionary dictionary : dlist) {
			map.put(dictionary.getCode(), new StaticInfo(dictionary.getTitle(), 0));
		}

		for (Question quest : this.questions) {
			StaticInfo info = map.get(quest.getChapter());
			if (info != null) {
				info.setNum(info.getNum() + 1);
			}
		}

		StringBuffer subxml = new StringBuffer("<chart  maxColWidth ='70' placeValuesInside ='1' caption='错题分布' labelStep='1' xAxisName='章节' yAxisName='数量'  showValues='1' numberSuffix ='题' baseFontSize ='12' rotateNames ='true'   >");
		Set<String> set = map.keySet();
		for (String key : set) {
			StaticInfo staticInfo = map.get(key);
			subxml.append("<set label='" + staticInfo.getTitle() + "' value='" + staticInfo.getNum() + "' />");
		}

		subxml.append("</chart> ");
		this.addAttribute("staXmls", subxml);

		return SUCCESS;
	}

	public Question getQuestion() {
		return question;
	}

	public void setQuestion(Question question) {
		this.question = question;
	}

	public Answer getAnswer() {
		return answer;
	}

	public void setAnswer(Answer answer) {
		this.answer = answer;
	}

	public Examination getExamination() {
		return examination;
	}

	public void setExamination(Examination examination) {
		this.examination = examination;
	}

	public boolean isContinueExam() {
		return continueExam;
	}

	public void setContinueExam(boolean continueExam) {
		this.continueExam = continueExam;
	}

	public List<Question> getQuestions() {
		return questions;
	}

	public void setQuestions(List<Question> questions) {
		this.questions = questions;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getLength() {
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}

	public String getOut() {
		return out;
	}

	public void setOut(String out) {
		this.out = out;
	}

}
